//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    id: '',
    mode: '',
    items: [],
    run_cash: 0,
    hide_modal: true,
    input_focus: false,
    cash: 0,
    is_host: false,
    host_name: '',
    is_over: false,
    win_side: 0,
    left_num: 0,
    rank: 0,
    rank_list: [],
    show_rank_input: false,
    opengid: 0,
    region: ['湖南省', '株洲市', '芦淞区'],
  },

  onLoad: function (opt) {
    this.data.id = opt.id
    wx.showShareMenu({
      withShareTicket: true,
    })
  },

  onShow: function (opt) {
    const that = this
    if (this.data.id) {
      that.renderWs()
    } else {
      app.request({
        url: app.root + 'round/create',
        success: function (res) {
          that.data.id = res.data.id
          that.renderWs()
        }
      })
    }
  },


  renderWs: function () {
    const that = this
    wx.showLoading({
      title: '连接中',
    })
    app.socket({
      // recheck when websocke connected
      gid: that.data.id,
      init: {
        url: app.root + 'round',
        method: 'post',
        data: {
          id: that.data.id
        },
        success: function (res) {
          wx.hideLoading()
          that.setData({
            cash: res.data.cash,
            mode: res.data.mode,
            is_host: res.data.is_host,
            host_name: res.data.host_name,
            is_over: res.data.is_over,
            win_side: res.data.win_side,
            rank: res.data.rank,
            area: res.data.area,
            rank_list: res.data.rank_list,
            // rank_update: res.data.rank_update,
            left_num: res.data.mode * 2 - res.data.items,
            items: that.createItems(res.data.items, res.data.mode)
          })
        }

      },

      success: function (res) {
        if (res.type == 'update') {
          that.setData({
            is_over: res.is_over,
            left_num: that.data.mode * 2 - res.items,
            items: that.createItems(res.items, that.data.mode)
          })
        }

        if (res.type == 'win_side') {
          that.setData({
            win_side: res.win_side
          })
        }

      }
    })
  },


  onWinBtn: function(e){
    const side = e.currentTarget.dataset.side
    const that = this
    wx.showModal({
      title: '提示',
      content: '确定' + side=='up' ? '上路' : '下路' + '胜利吗？',
      success: function(res){
        if(res.confirm){
          that.setData({
            win_side: side == 'up' ? 1 : 2,
            show_win_btn: false
          })
          app.request({
            url: app.root + 'round/winside',
            method: 'post',
            data:{
              id: that.data.id,
              side: side == 'up' ? 1 : 2
            },
            success: function(res){
              if(res.data.cash){
                wx.showModal({
                  title: '提示',
                  content: '恭喜您获得50%房费的推广奖励，再接再厉吧:)',
                  showCancel: false
                })
              }else{
                wx.showModal({
                  title: '提示',
                  content: '设置押金可以获得50%的房费哦，马上开一局吧:)',
                  showCancel: false
                })
              }
              
            }
          })
        }
      }
    })
  },

  onCreateBtn: function (e) {
    wx.navigateTo({
      url: '/pages/create/create',
    })
  },

  onCancelBtn: function (e) {
    this.setData({
      hide_modal: true
    })
  },

  onCashInput: function (e) {
    this.data.cash_input = Number(e.detail.value) || 0
  },

  onComfirmBtn: function (e) {
    if (this.clock == true) {
      return
    }
    this.clock = true

    const that = this
    const cash = this.data.cash
    wx.showLoading({
      title: '创建中',
    })

    app.request({
      url: app.root + 'round/create',
      method: 'post',
      data: {
        cash: this.data.cash_input
      },
      success: function (res) {
        wx.hideLoading()
        if (res.data.err) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false
          })
        } else {
          wx.reLaunch({
            url: '/pages/index/index?id=' + res.data.id,
            success: function () {
              that.clock = false
              wx.showModal({
                title: '提示',
                content: '创建成功，马上分享吧！',
                showCancel: false
              })
            }
          })
        }

      }

    })
  },

  onJoinBtn: function (e) {
    this.formId = e ? e.detail.formId : this.formId

    if (!this.data.rank || !this.data.area) {
      this.setData({
        show_rank_input: true
      })
      return
    }

    if (this.jlock == true) {
      return
    }
    this.jlock = true
    wx.showLoading({
      title: '加入中',
    })

    const that = this
    app.request({
      url: app.root + 'round/join',
      method: 'post',
      data: {
        formid: this.formId,
        id: this.data.id
      },
      success: function (res) {
        if (res.data.err) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false
          })
        } else {
          if (res.data.options) {
            const opt = res.data.options
            wx.requestPayment({
              'timeStamp': opt.timeStamp,
              'nonceStr': opt.nonceStr,
              'package': opt.package,
              'signType': 'MD5',
              'paySign': opt.paySign,
              'success': function (res) {
                wx.showModal({
                  title: '提示',
                  content: '加入成功',
                  showCancel: false
                })
              },
              'fail': function (res) {

              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false
            })
          }
        }
        that.jlock = false
        wx.hideLoading()
      }
    })
  },

  onRankSelect: function (e) {
    this.setData({
      rank: e.detail.value
    })
  },

  onRankConfirm: function (e) {
    if(!this.data.rank){
      return;
    }

    if (this.rlock) {
      return
    }
    this.rlock = true;

    const that = this
    wx.showLoading({
      title: '提交中',
    })

    app.request({
      url: app.root + 'round/rank',
      method: 'post',
      data: {
        rank: this.data.rank,
        region: this.data.region
      },
      success: function (res) {
        that.setData({
          show_rank_input: false,
          rank_update: false
        })
        that.rlock = false
        wx.hideLoading()
        that.onJoinBtn()
      }
    })

  },

  onQuestion: function (e) {
    // app.request({
    //   url: app.root + 'round/rules',
    //   success: function(res){
    //     wx.showModal({
    //       title: res.data.title,
    //       content: res.data.msg,
    //       showCancel: false
    //     })
    //   }
    // })

    wx.navigateTo({
      url: '/pages/question/question',
    })
  },

  onReport: function (e) {
    wx.navigateTo({
      url: '/pages/report/report',
    })
  },

  onRank: function (e){
    wx.navigateTo({
      url: '/pages/board/board',
    })
  },


  createItems: function (len, mode) {
    if (isNaN(len)) {
      return len
    }

    let items = []
    const number = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
    for (let i = 1; i < mode * 2 + 1; i++) {
      if (i <= len) {
        items.push({
          avatarUrl: '../../img/default.png',
          nickName: '玩家' + number[i - 1]
        })
      } else {
        items.push(i)
      }
    }

    return items
  },

  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },


  onShareAppMessage: function (res) {
    const that = this
    const mode = this.data.mode == 3 ? '3v3' : '5v5'
    let left = ''
    if (this.data.left_num > 0) {
      left = '(还差' + this.data.left_num + '人)'
    }
    return {
      title: this.data.host_name + '发起的' + mode + '随机分队' + left,
      path: '/pages/demo/demo?id=' + this.data.id,
      success: function (res) {
        console.log(res.shareTickets[0])
        wx.getShareInfo({
          shareTicket: res.shareTickets[0],
          success: function(data){
            app.request({
              url: app.root + 'round/setGid',
              method: 'post',
              data: {
                encryptedData: data.encryptedData,
                iv: data.iv,
                id: that.data.id
              },
              success: function(res){
                console.log(res)
              }
            })
          },
          fail: function(res){
            console.log(res)
          }
        })
        
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})
